package com.eningqu.aipen.demo.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.usb.UsbDevice;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eningqu.aipen.demo.BuildConfig;
import com.eningqu.aipen.demo.PenCtrlSdkManager;
import com.eningqu.aipen.demo.R;
import com.eningqu.aipen.demo.bean.NQPoint;
import com.eningqu.aipen.demo.common.Const;
import com.eningqu.aipen.demo.common.HttpUtils;
import com.eningqu.aipen.demo.databinding.ActivityMainSdkBinding;
import com.eningqu.aipen.demo.listener.TouchListener;
import com.eningqu.aipen.demo.view.CanvasDrawView;
import com.eningqu.aipen.demo.view.CanvasFrame;
import com.eningqu.aipen.sdk.ErrorCode;
import com.eningqu.aipen.sdk.NQPenSDK;
import com.eningqu.aipen.sdk.bean.DotType;
import com.eningqu.aipen.sdk.bean.NQDot;
import com.eningqu.aipen.sdk.bean.device.NQDeviceBase;
import com.eningqu.aipen.sdk.bean.device.NQUsbDevice;
import com.eningqu.aipen.sdk.comm.ConnectState;
import com.eningqu.aipen.sdk.comm.utils.BytesConvert;

import com.eningqu.aipen.sdk.listener.PenConnectListener;
import com.eningqu.aipen.sdk.listener.PenDotListener;
import com.eningqu.aipen.sdk.listener.PenMsgListener;
import com.eningqu.aipen.sdk.listener.PenOfflineDataListener;
import com.google.android.material.navigation.NavigationView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.databinding.DataBindingUtil;

import io.reactivex.functions.Consumer;


/**
 * @Author: Qiu.Li
 * @Create Date: 2020/3/8 14:41
 * @Description: demo主界面
 */
public class SDKMainActivity extends Activity {
    SharedPreferences pref;

    String m_stringVersion = "NQPenDemo";
    public String m_stringTerminationMessage = "退出Demo";
    public String m_stringTerminationYes = "确定";
    public String m_stringTerminationNo = "取消 ";

    private static final int REQUEST_SELECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    private static final int REQUEST_PERMISSION_LOCATION = 4;


    private NQDeviceBase mDevice = null;
    private BluetoothAdapter mBtAdapter = null;
    public Context mContext;

    private CanvasFrame mCurCanvasFrame;
    private CanvasDrawView mCurDrawView;

    /**
     * 笔画粗细
     */
    final private int THIN = 2;
    final private int NORMAL = 4;
    final private int THICK = 6;

    /**
     * 笔画颜色
     */
    final private int BLACK = 1;
    final private int RED = 2;
    final private int GREEN = 3;
    final private int BLUE = 4;

    final private static String SAVE_TEXT_INFO = "SAVE_TEXT_INFO";
    final private static String SAVE_TEXT_DATA = "SAVE_TEXT_DATA";


    private ArrayList<NQPoint> points = new ArrayList<NQPoint>();

    private int mActive;

    ActivityMainSdkBinding mBinding;
    private ActionBarDrawerToggle toggle;

    private boolean bShowToolbar = true;

    private boolean isA4Size = false;
    private StringBuilder mDotsSb = new StringBuilder();
    private float pageWHRatio = (float) 148 / 211;//纸张宽高比，默认a4

    private String mFwVersion = "";//固件版本信息
    private String mMCUVersion = "";//MCU版本信息
    private String mSerialNumber = "";//设备序列号

    private String mMac;//网卡mac地址
    private RxPermissions rxPermission;

    private long mOfflineDataDots = 0;//离线数据点数量

    public static void startAction(Context context){
        Intent intent=new Intent(context, SDKMainActivity.class);
        context.startActivity(intent);
    }

    private Handler mHandler = new Handler() {
        @Override

        //Handler events that received from UART service
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
            } else if (msg.what == 2) {
            }else if(msg.what==3){

                mBinding.tvPage.setText("Page:" + msg.arg1);
            }
        }
    };

    private SendThread sendThread;//实时转换字迹的线程
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        //固定竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main_sdk);
        mContext = this;
        //屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        pref = PreferenceManager.getDefaultSharedPreferences(mContext);
        mCurCanvasFrame = new CanvasFrame(mContext);
        mCurDrawView = mCurCanvasFrame.bDrawl;
        rxPermission = new RxPermissions(this);
        //初始化侧滑菜单
        initDrawerMenu();
        //初始化画板
        initDrawBroad(mBinding.flDrawBoard, mCurCanvasFrame);
        //初始化笔SDK
        intiPenSDK(NQPenSDK.CONN_TYPE.USB);
        //动态获取权限
        requestPermissions();
        //获取网卡Mac，也可以用其他唯一值来代替
        mMac = BytesConvert.bcdToString(HttpUtils.getMacFromHardware());
        if (sendThread == null) {
            sendThread = new SendThread(mMac, mCurDrawView,mHandler);
        }
        sendThread.setDaemon(true);
        sendThread.start();
    }

    /**
     * 侧滑菜单点击事件监听
     */
    NavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener = new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

            switch (menuItem.getItemId()) {
                case R.id.scan_usb://扫描usb
                    //关闭侧边栏
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    //检查设备是否支持USB的HOST模式
                    if (!supportUsbHost(mContext)) {
                        ToastUtils.showLong("This device is not support Usb host");
                    } else {
                        PenCtrlSdkManager.getInstance().release();
                        intiPenSDK(NQPenSDK.CONN_TYPE.USB);
                        startScanDeviceActivity();
                    }
                    break;
                case R.id.scan_ble://扫描蓝牙
                    //关闭侧边栏
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    //检查设备是否支持蓝牙
                    if (!isBluetoothAvailable()) {
                        ToastUtils.showLong("Bluetooth is not available");
                    } else {
                        PenCtrlSdkManager.getInstance().release();//释放原先的连接
                        intiPenSDK(NQPenSDK.CONN_TYPE.BLE);//初始化蓝牙连接
                        startScanDeviceActivity();//开始扫描
                    }
                    break;
                case R.id.sdk_version:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    String sdk = PenCtrlSdkManager.getInstance().requestSdkVersion();
                    ToastUtils.showShort("SDK Version:" + sdk);
                    break;
                case R.id.fw_version:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    PenCtrlSdkManager.getInstance().requestFirWareVersion();
                    break;
                case R.id.pen_bat:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    PenCtrlSdkManager.getInstance().requestBatInfo();
                    break;
                case R.id.mcu_version:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    break;
                case R.id.serial_number:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    PenCtrlSdkManager.getInstance().readDeviceSerialNumber();
                    break;
                case R.id.disconnect:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    if (PenCtrlSdkManager.getInstance().getConnState() != ConnectState.CONN_STATE_CONNECTED) {
                        ToastUtils.showShort("未连接设备");
                        break;
                    }
                    PenCtrlSdkManager.getInstance().disconnect();
                    break;
                case R.id.request_offline_data_length:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    //请求离线数据信息
                    PenCtrlSdkManager.getInstance().requestOfflineDataLength();
                    break;
                case R.id.request_offline_data_with_range:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    //请求离线数据
                    if (PenCtrlSdkManager.getInstance().getConnState() == ConnectState.CONN_STATE_CONNECTED) {
                        PenCtrlSdkManager.getInstance().requestOfflineDataWithRange(0, (int) mOfflineDataDots);
                    }
                    break;
                case R.id.request_delete_offline_data:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    //删除离线数据
                    PenCtrlSdkManager.getInstance().requestDeleteOfflineData();
                    break;
                case R.id.edit_ble_name:
                    mBinding.drawerLayout.closeDrawer(GravityCompat.START);
                    //修改蓝牙名称
                    showEditBleNameDialog();
                    break;
            }

            return false;
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_LOCATION) {
            if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != 0 ||
                    ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != 0) {
                ActivityCompat.requestPermissions(SDKMainActivity.this,    // onRequestPermissionsResult()へ
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_LOCATION);
            } else {
                if (CheckStartConditions() == 0)
                    startScanDeviceActivity();
            }
        }
    }

    /**
     * 初始化侧滑菜单
     */
    private void initDrawerMenu() {
        //创建返回键，并实现打开关/闭监听
        toggle = new ActionBarDrawerToggle(this,
                mBinding.drawerLayout, mBinding.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);

                Menu menu = mBinding.navigationView.getMenu();
//                MenuItem menuItem = menu.findItem(R.id.sdk_version);
                menu.findItem(R.id.sdk_version).setTitle("    SDK版本" + "  " + com.eningqu.aipen.sdk.BuildConfig.VERSION_NAME);
                menu.findItem(R.id.fw_version).setTitle("    固件版本" + "  " + mFwVersion);
                menu.findItem(R.id.mcu_version).setTitle("    MCU版本" + "  " + mMCUVersion);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);

            }
        };

        mBinding.drawerLayout.addDrawerListener(toggle);

        toggle.syncState();

        //默认打开
        mBinding.drawerLayout.openDrawer(GravityCompat.START);

        //设置条目点击监听
        mBinding.navigationView.setNavigationItemSelectedListener(navigationItemSelectedListener);
        mBinding.includeMenuFooter.llRoot.setVisibility(View.INVISIBLE);
        mBinding.includeMenuFooter.switchOriginPoint.setText("适配A4");
        pref.edit().putString(Const.Pref.KEY_PAGE_SIZE, "a5");
        mBinding.includeMenuFooter.switchOriginPoint.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                isA4Size = isChecked;


                if (isChecked) {

                    pref.edit().putString(Const.Pref.KEY_PAGE_SIZE, "a4");
                    pageWHRatio = (float) 210 / 297;
                    PenCtrlSdkManager.getInstance().setPageSizeForA4();
                } else {

                    pref.edit().putString(Const.Pref.KEY_PAGE_SIZE, "a5");
                    pageWHRatio = (float) 148 / 211;
                    PenCtrlSdkManager.getInstance().setPageSizeForA5();
                }

                if (null != mCurCanvasFrame) {

                    int width = ScreenUtils.getScreenWidth();
                    int height = (int) ((float) ScreenUtils.getScreenWidth() / pageWHRatio);

                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
                    layoutParams.width = ScreenUtils.getScreenWidth();

                    mCurCanvasFrame.setLayoutParams(layoutParams);
                    mCurCanvasFrame.invalidate();
                }
            }
        });

        isA4Size = "a4".equals(pref.getString(Const.Pref.KEY_PAGE_SIZE, "a4"));

        mBinding.includeMenuFooter.switchOriginPoint.setChecked(isA4Size);

        mBinding.includeMenuFooter.llRecvDots.setVisibility(View.GONE);
        mBinding.includeMenuFooter.tvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.includeMenuFooter.llRoot.setVisibility(View.GONE);
            }
        });

        mBinding.ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDotsSb.length() > 1) {
                    mDotsSb.delete(0, mDotsSb.length() - 1);
                    mBinding.includeMenuFooter.tvRecvDots.setText("");
                }
                if (null != mCurDrawView) {

                    mCurDrawView.cleanCanvas();
                }
            }
        });

        mBinding.includePenSize.ivPenSizeThin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mBinding.includePenSize.ivPenSizeMid.setBackground(null);
                mBinding.includePenSize.ivPenSizeThick.setBackground(null);
                mBinding.includePenSize.ivPenSizeThin.setBackgroundResource(R.drawable.shape_color_bg_white);

                mCurCanvasFrame.bDrawl.setSize(THIN);
                pref.edit().putInt(Const.Pref.KEY_THICKNESS, THIN).commit();
            }
        });

        mBinding.includePenSize.ivPenSizeMid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.includePenSize.ivPenSizeMid.setBackgroundResource(R.drawable.shape_color_bg_white);
                mBinding.includePenSize.ivPenSizeThick.setBackground(null);
                mBinding.includePenSize.ivPenSizeThin.setBackground(null);

                mCurCanvasFrame.bDrawl.setSize(NORMAL);
                pref.edit().putInt(Const.Pref.KEY_THICKNESS, NORMAL).commit();
            }
        });

        mBinding.includePenSize.ivPenSizeThick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.includePenSize.ivPenSizeMid.setBackground(null);
                mBinding.includePenSize.ivPenSizeThick.setBackgroundResource(R.drawable.shape_color_bg_white);
                mBinding.includePenSize.ivPenSizeThin.setBackground(null);

                mCurCanvasFrame.bDrawl.setSize(THICK);
                pref.edit().putInt(Const.Pref.KEY_THICKNESS, THICK).commit();
            }
        });

        //black
        mBinding.includePenColor.ivPenColorBlack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.includePenColor.ivPenColorBlack.setBackgroundResource(R.drawable.shape_color_bg_white);
                mBinding.includePenColor.ivPenColorRed.setBackground(null);
                mBinding.includePenColor.ivPenColorGreen.setBackground(null);
                mBinding.includePenColor.ivPenColorBlue.setBackground(null);

                mCurCanvasFrame.bDrawl.setColor(ContextCompat.getColor(mContext, R.color.color_000000));
                pref.edit().putInt(Const.Pref.KEY_COLOR, BLACK).commit();
            }
        });

        //red
        mBinding.includePenColor.ivPenColorRed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.includePenColor.ivPenColorRed.setBackgroundResource(R.drawable.shape_color_bg_white);
                mBinding.includePenColor.ivPenColorBlack.setBackground(null);
                mBinding.includePenColor.ivPenColorGreen.setBackground(null);
                mBinding.includePenColor.ivPenColorBlue.setBackground(null);

                mCurCanvasFrame.bDrawl.setColor(ContextCompat.getColor(mContext, R.color.color_E60012));
                pref.edit().putInt(Const.Pref.KEY_COLOR, BLACK).commit();
            }
        });

        //green
        mBinding.includePenColor.ivPenColorGreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.includePenColor.ivPenColorGreen.setBackgroundResource(R.drawable.shape_color_bg_white);
                mBinding.includePenColor.ivPenColorRed.setBackground(null);
                mBinding.includePenColor.ivPenColorBlack.setBackground(null);
                mBinding.includePenColor.ivPenColorBlue.setBackground(null);

                mCurCanvasFrame.bDrawl.setColor(ContextCompat.getColor(mContext, R.color.color_45D151));
            }
        });

        //blue
        mBinding.includePenColor.ivPenColorBlue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.includePenColor.ivPenColorBlue.setBackgroundResource(R.drawable.shape_color_bg_white);
                mBinding.includePenColor.ivPenColorRed.setBackground(null);
                mBinding.includePenColor.ivPenColorGreen.setBackground(null);
                mBinding.includePenColor.ivPenColorBlack.setBackground(null);

                mCurCanvasFrame.bDrawl.setColor(ContextCompat.getColor(mContext, R.color.color_0D7993));
            }
        });


        int penSize = pref.getInt(Const.Pref.KEY_THICKNESS, THIN);
        int penColour = pref.getInt(Const.Pref.KEY_COLOR, BLACK);


        View headerView = mBinding.navigationView.getHeaderView(0);
        if (null != headerView) {

            TextView textView = headerView.findViewById(R.id.tv_head_name);

            if (null != textView) {

                textView.setText(BuildConfig.VERSION_NAME);
            }
        }
    }

    /**
     * 初始化笔SDK
     */
    private void intiPenSDK(NQPenSDK.CONN_TYPE connType) {
        //sdk管理单例到初始化，PenCtrlSdkManager是智能笔SDK管理单例，对sdk进行二次封装
        PenCtrlSdkManager.getInstance().init(getApplication(), connType);
        //添加监听器
        setPenListener();
        //开始搜索
        PenCtrlSdkManager.getInstance().startScanDevice();
    }

    /**
     * 设置各类事件监听
     */
    private void setPenListener() {
        //设置实时书写点接收监听
        PenCtrlSdkManager.getInstance().setDotListener(penDotListener);
        //监听离线同步数据
        PenCtrlSdkManager.getInstance().setPenOfflineDataListener(offlineDataListener);
        //设置连接监听
        PenCtrlSdkManager.getInstance().setConnectListener(connectListener);
        //设置笔信息监听
        PenCtrlSdkManager.getInstance().setPenMsgListener(penMsgListener);
    }

    /**
     * Activity 点击事件
     */
    public void onMyClick(View view) {
    }

    /**
     * 初始化画板
     */
    private void initDrawBroad(@NonNull final FrameLayout frameLayout, @NonNull final CanvasFrame canvasFrame) {

        if (canvasFrame.initDrawBroad) {
            LogUtils.d("已装载画板");
            return;
        }

        LogUtils.d("装载画板");

        frameLayout.post(new Runnable() {
            public void run() {


            int width = ScreenUtils.getScreenWidth();
            int height = (int) ((float) ScreenUtils.getScreenWidth() / pageWHRatio);

            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
            layoutParams.width = ScreenUtils.getScreenWidth();

            canvasFrame.setLayoutParams(layoutParams);

            final CanvasDrawView drawView = canvasFrame.bDrawl;
            if (null != drawView) {
                drawView.setZOrderOnTop(true); // 在最顶层，会遮挡一切view
                drawView.setZOrderMediaOverlay(true);// 如已绘制SurfaceView则在surfaceView上一层绘制。
                drawView.setDrawing(true);
            }

            canvasFrame.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
//                                mCanvasHeight = drawView.getHeight();
//                                mCanvasWidth = drawView.getWidth();
                            LogUtils.d("onGlobalLayout 设置触摸监听");
                            canvasFrame.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            if (null != frameLayout) {

                                frameLayout.setOnTouchListener(new TouchListener(canvasFrame, frameLayout.getWidth(),
                                        frameLayout.getHeight(), canvasFrame.getMeasuredWidth(), canvasFrame.getMeasuredHeight()));
                            }

                            //设置笔默认的颜色和大小
                                setDefaultPenSizeAndColour();

                            canvasFrame.initDrawBroad = true;
                        }
                    });

            frameLayout.removeAllViews();
            frameLayout.addView(canvasFrame);
            }
        });
    }

    /**
     * 检查设备是否支持蓝牙
     *
     * @return
     */
    private boolean isBluetoothAvailable() {
        // 检查蓝牙适配器,由于P10和P11项目公用一个DEMO,所以，会保留部分BLE的代码
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
            return false;
        }
        return true;
    }

    /**
     * 是否支持USB HOST
     *
     * @return
     */
    public boolean supportUsbHost(Context context) {
        return context.getPackageManager().hasSystemFeature("android.hardware.usb.host");
    }

    /**
     * 蓝牙设备检查启动的条件，usb不需要
     *
     * @return
     */
    private int CheckStartConditions() {
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            return REQUEST_ENABLE_BT;
        }

        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != 0 ||
                ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != 0) {
            ActivityCompat.requestPermissions(SDKMainActivity.this,    // onRequestPermissionsResult()へ
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_LOCATION);
            return REQUEST_PERMISSION_LOCATION;
        }
        return 0;
    }


    @Override
    public void onStart() {
        super.onStart();

    }

    /**
     * 设置笔默认的颜色和大小
     */
    private void setDefaultPenSizeAndColour() {
        LogUtils.d("设置笔默认的颜色和大小");
        //获取缓存的笔画粗细,默认THIN
        int thickness = pref.getInt(Const.Pref.KEY_THICKNESS, THIN);
        Message message = Message.obtain();
        message.what = 1;
        switch (thickness) {
            case THIN:
                message.arg1 = 1;
                break;
            case NORMAL:
                message.arg1 = 2;
                break;
            case THICK:
                message.arg1 = 3;
                break;
        }

        //获取缓存的笔画颜色,默认BLACK
        int color = pref.getInt(Const.Pref.KEY_COLOR, BLACK);
        switch (color) {
            case BLACK:
                message.arg2 = 1;
                break;
            case RED:
                message.arg2 = 2;
                break;
            case GREEN:
                message.arg2 = 3;
                break;
            case BLUE:
                message.arg2 = 4;
                break;
        }
        mHandler.sendMessage(message);
    }


    /**
     * 扫描设备
     */
    private void startScanDeviceActivity() {
        if (!(ActivityUtils.getTopActivity() instanceof DeviceListActivity)) {

            Intent deviceScan = new Intent(mContext, DeviceListActivity.class);
//            startActivityForResult(deviceScan, REQUEST_SELECT_DEVICE);
            startActivity(deviceScan);
        }
    }

    /**
     * 实时书写点监听
     */
    PenDotListener penDotListener = new PenDotListener() {
        @Override
        public void onReceiveDot(final NQDot nqDot) {

//            LogUtils.d("本地SDK返回: type=" + nqDot.type + "， dot.x=" + nqDot.x + " dot.y=" + nqDot.y
//                    + ", page=" + nqDot.page + "，bookNum=" + nqDot.bookNum
//                    + ", Width=" + nqDot.book_width + ", Height=" + nqDot.book_height);
//
//            if (mDotsSb.length() > 4096) {
//                //避免数据太多，及时清理
//                mDotsSb.delete(0, 1024);
//            }
//
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    mBinding.tvPage.setText("Page:" + nqDot.page);
//                    mCurDrawView.addDot(mMac, nqDot);
//                }
//            });
//
//            if (nqDot.type == DotType.PEN_ACTION_DOWN) {
//                //按下笔
//                mDotsSb.append("(" + nqDot.x).append(",").append(nqDot.y + ")").append("  Down\n");
//            } else if (nqDot.type == DotType.PEN_ACTION_MOVE) {
//                //移动笔
//                mDotsSb.append("(" + nqDot.x).append(",").append(nqDot.y + ")").append("  Move\n");
//            } else if (nqDot.type == DotType.PEN_ACTION_UP) {
//                //抬起笔
//                mDotsSb.append("(" + nqDot.x).append(",").append(nqDot.y + ")").append("  Up\n");
////                mnPreXvalue = 0;
//            }
//
//
//            //判断侧滑菜单是否打开
//            if (mBinding.drawerLayout.isDrawerOpen(mBinding.navigationView)) {
//
//                //在ui上显示点信息
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        mBinding.includeMenuFooter.tvRecvDots.setText(mDotsSb.toString());
//                        mBinding.includeMenuFooter.scrollView.fullScroll(View.FOCUS_DOWN);
//                    }
//                });
//            }
            nqDotQueue.add(nqDot);
            sendThread.resumeThread();
        }

        @Override
        public void onError(int error, String message) {
            ToastUtils.showLong("异常信息: Msg=" + message + "， error=" + error);
            /*if (error == 121) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new AlertDialog.Builder(SDKMainActivity.this)
                                .setTitle(m_stringVersion)///m_strDBVersion
                                .setMessage("抬笔点的页码和之前页码不一致")
                                .setPositiveButton(m_stringTerminationYes, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
//                        if (null != mDrawView) {
//                            mDrawView.drawHelper.canRun = false;
//                            mDrawView.drawHelper.stopThread();
//                        }
                                    }
                                })
                                .setNegativeButton(m_stringTerminationNo, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                })
                                .show();
                    }
                });

            }*/
        }
    };

    private static Queue<NQDot> nqDotQueue = new ConcurrentLinkedQueue<>();

    private static class SendThread extends Thread {
        private final Object lock = new Object();

        private String mac;
        private CanvasDrawView canvasDrawView;
        private int page=-1;
        private Handler handler;

        public  SendThread(String mac, CanvasDrawView canvasDrawView,Handler handler) {
            this.mac = mac;
            this.canvasDrawView = canvasDrawView;
            this.handler=handler;
        }

        void resumeThread() {
            synchronized (lock) {
                lock.notify();
            }
        }

        void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            while (true) {
                while (!nqDotQueue.isEmpty()) {
                    NQDot nqDot=nqDotQueue.poll();
                    LogUtils.d("本地SDK返回: type=" + nqDot.type + "， dot.x=" + nqDot.x + " dot.y=" + nqDot.y
                            + ", page=" + nqDot.page + "，bookNum=" + nqDot.bookNum
                            + ", Width=" + nqDot.book_width + ", Height=" + nqDot.book_height);

                    if(page==-1){//第一次更新页面信息
                        page=nqDot.page;
                    }else {
                        if(page!=nqDot.page){//点阵笔迹携带的页面信息与界面展示的界面信息不一样
                            Message message= new Message();
                            page=nqDot.page;
                            message.what=3;
                            message.arg1=page;
                            handler.sendMessage(message);
                        }
                    }

                    canvasDrawView.addDot(mac, nqDot);
                }
                onPause();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                if (CheckStartConditions() == 0)
                    startScanDeviceActivity();
                break;
            default:
                LogUtils.e("wrong request code");
                break;
        }
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        //设置实时书写点接收监听
        PenCtrlSdkManager.getInstance().setDotListener(penDotListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // TODO Auto-generated method stub
        mBinding.drawerLayout.closeDrawer(GravityCompat.START);
    }


    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.d("onStop()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d("onDestroy()");

        //释放资源
        if (null != mCurDrawView) {
            mCurDrawView.setDrawing(false);
        }
        PenCtrlSdkManager.getInstance().release();

        if (null != mCurCanvasFrame) {
            mCurCanvasFrame.bDrawl = null;
        }
        mCurCanvasFrame = null;
        mBinding = null;
    }


    /**
     * 确认退出程序
     */
    public void processFinishProgram() {

        new AlertDialog.Builder(this)
                .setTitle(m_stringVersion)///m_strDBVersion
                .setMessage(m_stringTerminationMessage)
                .setPositiveButton(m_stringTerminationYes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        finish();
//                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                })
                .setNegativeButton(m_stringTerminationNo, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();

    }

    @Override
    public void onBackPressed() {
        if (mBinding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            mBinding.drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            //退出程序
            processFinishProgram();
        }

    }

    private void showConnState(final String connState) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                View headerView = mBinding.navigationView.getHeaderView(0);
                if (null != headerView) {

                    TextView textView = headerView.findViewById(R.id.tv_conn_state);

                    if (null != textView) {

                        textView.setText("连接状态：" + connState);
                    }
                }
            }
        });
    }

    private void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showShort(msg);
            }
        });
    }

    /**
     * 连接回调
     */
    PenConnectListener connectListener = new PenConnectListener() {


        @Override
        public void onConnectState(int i) {
            LogUtils.d("onConnectState state=" + i);
            if (i == ConnectState.CONN_STATE_CONNECTED) {
                ToastUtils.showLong("连接成功 state=" + i);
                showConnState("连接成功");
            } else if (i == ConnectState.CONN_STATE_CONNECTING) {
                ToastUtils.showLong("连接中... state=" + i);
                showConnState("连接中...");
            } else if (i == ConnectState.CONN_STATE_DISCONNECTING) {
                ToastUtils.showLong("断开连接中... state=" + i);
                showConnState("断开连接中...");
            } else if (i == ConnectState.CONN_STATE_CLOSED) {
                ToastUtils.showLong("连接断开... state=" + i);
                showConnState("连接断开");
            }
        }

        @Override
        public void onUsbDeviceAttached(UsbDevice usbDevice) {
            LogUtils.i("usb device attached...");
            ToastUtils.showLong("插入USB设备");
            NQUsbDevice deviceBase = new NQUsbDevice();
            deviceBase.setDevice(usbDevice);
            PenCtrlSdkManager.getInstance().setCurNQDev(deviceBase);
//            startScanDeviceActivity();
            PenCtrlSdkManager.getInstance().connect(deviceBase);
        }

        @Override
        public void onUsbDeviceDetached(UsbDevice usbDevice) {
            LogUtils.i("usb device detached...");
            ToastUtils.showLong("拔出USB设备");
            showConnState("连接断开");
            PenCtrlSdkManager.getInstance().setCurNQDev(null);
            startScanDeviceActivity();
        }

        @Override
        public void onReceiveException(int i, String s) {
            LogUtils.e("receiveException error=" + i + ", message=" + s);
            if (i == ErrorCode.ERR_CONN_CONNECT) {
                ToastUtils.showLong("连接断开... error=" + i);
                showConnState("连接断开");
            }
        }


//        @Override
//        public void onScanStart() {
//            LogUtils.i("scan device start...");
//        }
//
//        @Override
//        public void onScanStop() {
//            LogUtils.i("scan device stop...");
//        }
//
//        @Override
//        public void onReceiveException(int i, String s) {
//            LogUtils.e("receiveException error=" + i + ", message=" + s);
//            if (i == ErrorCode.ERR_CONN_CONNECT) {
//                ToastUtils.showLong("连接断开... error=" + i);
//                showConnState("连接断开");
//            }
//        }
//
//        @Override
//        public void onScanResult(NQDeviceBase nqDeviceBase) {
//            LogUtils.i("scan device result:" + nqDeviceBase.toString());
//        }
//
//        @Override
//        public void onConnectState(int i) {
//            LogUtils.d("onConnectState state=" + i);
//            if (i == ConnectState.CONN_STATE_CONNECTED) {
//                ToastUtils.showLong("连接成功 state=" + i);
//                showConnState("连接成功");
//            } else if (i == ConnectState.CONN_STATE_CONNECTING) {
//                ToastUtils.showLong("连接中... state=" + i);
//                showConnState("连接中...");
//            } else if (i == ConnectState.CONN_STATE_DISCONNECTING) {
//                ToastUtils.showLong("断开连接中... state=" + i);
//                showConnState("断开连接中...");
//            } else if (i == ConnectState.CONN_STATE_CLOSED) {
//                ToastUtils.showLong("连接断开... state=" + i);
//                showConnState("连接断开");
//            }
//        }
//
//        @Override
//        public void onUsbDeviceAttached(UsbDevice usbDevice) {
//            LogUtils.i("usb device attached...");
//            ToastUtils.showLong("插入USB设备");
//            NQUsbDevice deviceBase = new NQUsbDevice();
//            deviceBase.setDevice(usbDevice);
//            PenCtrlSdkManager.getInstance().setCurNQDev(deviceBase);
////            startScanDeviceActivity();
//            PenCtrlSdkManager.getInstance().connect(deviceBase);
//        }
//
//        @Override
//        public void onUsbDeviceDetached(UsbDevice usbDevice) {
//            LogUtils.i("usb device detached...");
//            ToastUtils.showLong("拔出USB设备");
//            showConnState("连接断开");
//            PenCtrlSdkManager.getInstance().setCurNQDev(null);
//            startScanDeviceActivity();
//        }
    };


    PenMsgListener penMsgListener = new PenMsgListener() {
        @Override
        public void onEditName(String s) {

        }

        @Override
        public void bleVersion(String s) {

        }

        @Override
        public void onFWVer(String s) {
//            LogUtils.d("固件版本：" + ver);
            mFwVersion = s;
            showToast("固件版本：" + s);
        }

        @Override
        public void onMCUVer(String s) {
//            LogUtils.d("MCU版本：" + ver);
            mMCUVersion = s;
            showToast("MCU版本：" + s);
        }

        @Override
        public void onBatInfo(float v) {
            showToast("电压：" + v);
        }

        @Override
        public void onFlashUsedAmount(int i) {

        }

        @Override
        public void onSerialNumber(String s) {
            //序列号
            mSerialNumber = s;
            showToast("序列号：" + s);
        }


//        @Override
//        public void onFWVer(String ver) {
////            LogUtils.d("固件版本：" + ver);
//            mFwVersion = ver;
//            showToast("固件版本："+ver);
//        }
//
//        @Override
//        public void onMCUVer(String ver) {
////            LogUtils.d("MCU版本：" + ver);
//            mMCUVersion = ver;
//            showToast("MCU版本："+ver);
//        }
//
//        @Override
//        public void onBatInfo(float bat) {
//            showToast("电压："+bat);
//        }
//
//        @Override
//        public void onSerialNumber(String s) {
//            //序列号
//            mSerialNumber = s;
//            showToast("序列号："+s);
//        }
    };


    /**
     * 动态权限
     */
    @SuppressLint("CheckResult")
    private void requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            rxPermission.request(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA
            ).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean) {
//                        isCancelPermission = true;
//                        //完成授权
//                        //开始扫描蓝牙设备，自动连接
//                        if (!isCancelBtEnable) {
//                            openBluetoothAndLocation(SDKMainActivity.this);
//                        }
                    } else {
                    }
                }
            });
        } else {
        }
    }

    /**
     * 修改蓝牙名称对话框
     */
    private void showEditBleNameDialog() {

        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_edit_blename, null);//这里必须是final的
        final EditText edit = (EditText) view.findViewById(R.id.editBleName);//获得输入框对象

        new AlertDialog.Builder(SDKMainActivity.this)
                .setTitle("修改蓝牙名称")
                .setView(view)
                .setPositiveButton(m_stringTerminationYes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String newBtName = edit.getText().toString().trim();
                        PenCtrlSdkManager.getInstance().editBleDeviceName(newBtName);
                    }
                })
                .setNegativeButton(m_stringTerminationNo, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }

    PenOfflineDataListener offlineDataListener = new PenOfflineDataListener() {
        @Override
        public void offlineDataSyncStart(long l) {
            showToast("开始同步离线数据 Len=" + l + " byte");
        }

        @Override
        public void offlineDataSyncStop() {
            mBinding.drawerLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    PenCtrlSdkManager.getInstance().requestDeleteOfflineData();
                }
            }, 2000);
            showToast("同步完成");
        }

        @Override
        public void offlineDataDidReceivePenData(final NQDot nqDot) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                        LogUtils.d("离线数据本地SDK返回: type=" + nqDot.type + "， dot.x=" + nqDot.x + " dot.y=" + nqDot.y
//                                + ", page=" + nqDot.page + "，bookNum=" + nqDot.bookNum
//                                + ", Width=" + nqDot.book_width + ", Height=" + nqDot.book_height);
                    mCurDrawView.addDot(mMac, nqDot);
                    if (nqDot.type == DotType.PEN_ACTION_DOWN) {
                        mBinding.tvPage.setText("Page:" + nqDot.page);
                    }
                }
            });
        }

        @Override
        public void offlineDataDel() {
            showToast("成功删除离线数据");
        }

        @Override
        public void offlineDataLength(long l) {
            showToast("离线数据数量:" + l);
            mOfflineDataDots = l;
        }

        @Override
        public void onOffLineCurrentDataLength(long l) {

        }

    };
}




